<template>
    <div class="study_plan_container">
        <div class="study_plan">
            <!-- <div class="actions">
                <button @click="addPlan" disabled class="disabled-button">添加计划</button>
            </div> -->
            <table>
                <thead>
                    <tr>
                        <th><input type="checkbox" v-model="selectAll" @change="toggleSelectAll" /> 全选</th>
                        <th>序号</th>
                        <th>学生姓名</th>
                        <th>每日新任务</th>
                        <th>每日复习</th>
                        <th>最大重复次数</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <tr v-for="plan in plans" :key="plan.id">
                        <td><input type="checkbox" v-model="selectedPlans" :value="plan.id" /></td>
                        <td>{{ plan.config_id }}</td>
                        <td>{{ plan.student_name }}</td>
                        <td>{{ plan.daily_new }}</td>
                        <td>{{ plan.daily_review }}</td>
                        <td>{{ plan.max_repeat }}</td>
                        <td class="action-buttons">
                            <button @click="editPlan(plan)">编辑</button>
                            <button @click="deletePlan(plan.config_id)">删除</button>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { ApiService } from '@/api/apiService';
import { useUserStore } from '@/stores/user';

const userStore = useUserStore();

// 学习计划数据
const plans = ref([]);
// 初始化数据
async function fetchItems() {
    // try {
    const userId = userStore.getUser?.user_id;
    if (!userId) throw new Error('User ID not found');

    const response = await ApiService.get_plan_config(userId);
    console.log('获取学习计划成功:', response.data.code);
    if (response.data.code === 200) {
        plans.value = response.data.data;
    } else {
        console.error('获取学习计划失败:', response.data);
    }
    // } catch (error) {
    //     console.error('error:', error);
    // }
}

onMounted(() => {
    fetchItems();
});


// 选中的计划ID列表
const selectedPlans = ref([]);

// 全选状态
const selectAll = ref(false);

// 全选/取消全选
const toggleSelectAll = () => {
    if (selectAll.value) {
        selectedPlans.value = plans.value.map(plan => plan.id);
    } else {
        selectedPlans.value = [];
    }
};

// 添加计划
const addPlan = () => {
    const newPlan = {
        id: plans.value.length + 1,
        studentName: '新学生',
        dailyNew: 5,
        dailyReview: 3,
        maxRepeat: 5,
    };
    plans.value.push(newPlan);
};

// 删除选中计划
const deleteSelected = () => {
    plans.value = plans.value.filter(plan => !selectedPlans.value.includes(plan.id));
    selectedPlans.value = [];
    selectAll.value = false;
};


// 编辑计划
const editPlan = async (plan) => {
    console.log('编辑计划:', plan);

    // 使用模板字符串和默认值优化提示信息
    const daily_new = prompt(`请输入每日新任务数量（当前值: ${plan.daily_new}）:`, plan.daily_new);
    const daily_review = prompt(`请输入每日复习数量（当前值: ${plan.daily_review}）:`, plan.daily_review);
    const max_repeat = prompt(`请输入最大重复次数（当前值: ${plan.max_repeat}）:`, plan.max_repeat);

    // 检查输入是否有效
    if (daily_new === null || daily_review === null || max_repeat === null) {
        console.log('用户取消了编辑');
        return;
    }

    if (!daily_new || !daily_review || !max_repeat) {
        alert('输入不能为空，请重新填写！');
        return;
    }

    // 将输入转换为数字
    const newDailyNew = parseInt(daily_new);
    const newDailyReview = parseInt(daily_review);
    const newMaxRepeat = parseInt(max_repeat);

    // 检查是否为有效数字
    if (isNaN(newDailyNew) || isNaN(newDailyReview) || isNaN(newMaxRepeat)) {
        alert('请输入有效的数字！');
        return;
    }

    // 更新计划
    plan.daily_new = newDailyNew;
    plan.daily_review = newDailyReview;
    plan.max_repeat = newMaxRepeat;

    try {
        // 调用 API 更新计划
        const response = await ApiService.update_plan(plan.config_id, {
            daily_new: plan.daily_new,
            daily_review: plan.daily_review,
            max_repeat: plan.max_repeat,
        });

        // 检查响应状态
        if (response.data.code === 200) {
            alert('修改学习计划成功！');
            fetchItems(); // 重新加载数据
        } else {
            console.error('修改学习计划失败:', response.data);
            alert('修改学习计划失败，请稍后重试！');
        }
    } catch (error) {
        console.error('请求出错:', error);
        alert('请求出错，请稍后重试！');
    }

    console.log('修改后的计划:', plan);
};

// 删除单个计划
const deletePlan = async (id) => {
    const response = await ApiService.delete_plan_config(id);
    if (response.data.code === 200) {
        fetchItems();
    } else {
        console.error('删除学习计划失败:', response.data);
    }
};
</script>

<style scoped>
    @import url("@/assets/css/study_plan.css");
</style>